import { createStore, combineReducers, applyMiddleware } from "redux";
// 引入 redux devtools
import { composeWithDevTools } from "@redux-devtools/extension";

// 引入子Reducer
import appReducer from "./reducers/app";
import userReducer from "./reducers/usre";

// 通过 composeReducers 来组装 rootReducer
const rootReducer = combineReducers({
  app: appReducer,
  user: userReducer,
});

/**
 * 日志记录中间件
 *    需求：一个动作派发前后，输出仓库中的 state 数据情况
 */
const logger = (storeApi) => (next) => (action) => {
  // 处理中间件逻辑的地方

  // 1. 打印当前的 state 数据
  console.log("prev", storeApi.getState());
  // 2. 调用下一个中间件或者真实的 store.dispatch
  const result = next(action);
  // 3. 打印当前的 state 数据
  console.log("next", storeApi.getState());

  // 4. end 将 next() 的结果给 返回
  return result;
};

/**
 * 测试中间件1
 */
function test1(storeApi) {
  return function warp(next) {
    return function handle(action) {
      console.log("test1");
      // 处理逻辑
      const result = next(action);
      console.log("test1 result", result);
    };
  };
}

function test2(storeApi) {
  return function warp(next) {
    return function handle(action) {
      console.log("test2");

      // storeApi.dispatch 重启中间件
      // storeApi.dispatch({ type: "SET_TOKEN", payload: "王五" });

      if (action.payload === "张三") {
        storeApi.dispatch({ type: "SET_TOKEN", payload: "王五" });
      } else {
        return next(action);
      }
    };
  };
}

function test3(storeApi) {
  return function warp(next) {
    return function handle(action) {
      console.log("test3");
      // 处理逻辑
      return next(action);
    };
  };
}

// 创建 store
const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(test1, test2, test3))
);

export default store;
